package com.szewec.ps.ui.road.facilities.investigation.task;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseMediaPickerActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.base.FileUpload;
import com.szewec.ps.databinding.ActivityRoadMotorwayBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTask;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTaskDTO;
import com.szewec.ps.model.road.facilities.investigation.task.RoadMotorway;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.imagepicker.adapter.CustomPickerAdapterShowAndEdit;
import com.szewec.ps.util.imagepicker.data.MediaFile;

import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class RoadMotorwayActivity extends BaseMediaPickerActivity {
    private ActivityRoadMotorwayBinding binding;

    /********字典start***********/
    // 车道总数
    private ArrayList<String> laneTotalDict = new ArrayList<>();
    // 辅路
    private ArrayList<String> serviceRoadDict = new ArrayList<>();
    // 第几道数
    private ArrayList<String> numberOfLanesDict = new ArrayList<>();
    // 车道类型
    private ArrayList<String> laneTypeDict = new ArrayList<>();
    // 铺面形式
    private ArrayList<String> pavementFormDict = new ArrayList<>();
    /********字典end***********/
    private String modeFlag; // 用于区分新增还是修改还是详情展示
    private ViewModeValue viewModeValue;
    private RoadMotorway roadMotorway = new RoadMotorway();
    // 路段设施调查任务DTO
    private RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO roadFacilitiesTaskDTO;

    // 照片上传数组
    private List<String> photoSketchUploadIdArr = new ArrayList<>();
    // 照片文件数组
    private ArrayList<MediaFile> photoSketchFileArr = new ArrayList<>();
    // 图片适配器
    private CustomPickerAdapterShowAndEdit photoSketchAdapter;
    // 移除的图片ID数组
    private List<String> deletePhotoIdArr = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_road_motorway);
        ButterKnife.bind(this);
        initData();
        initView();
        initTitleBar();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 初始化字典
        laneTotalDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.laneTotal)));
        serviceRoadDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.serviceRoad)));
        laneTypeDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.laneType)));
        pavementFormDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.pavementForm)));

        // 获取intent中的数据
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue =
                (PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO>) getIntent().
                        getSerializableExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO);
        //获取是新增还是修改还是详情展示
        assert presentValue != null;
        modeFlag = presentValue.getFlag();
        roadFacilitiesTaskDTO = presentValue.getT();
        Log.i("机动车道getData", JSONObject.toJSONString(roadFacilitiesTaskDTO));
    }

    /**
     * 初始化界面样式
     */
    private void initView() {
        roadMotorway = roadFacilitiesTaskDTO.getRoadMotorway() == null ? new RoadMotorway() : roadFacilitiesTaskDTO.getRoadMotorway();

        // 初始化照片适配器
        photoSketchAdapter = initTypeMediaRecyclerView(photoSketchUploadIdArr, photoSketchFileArr,
                binding.photoSketchSketchRV, true, false, true, deletePhotoIdArr);

        Integer laneTotal = roadMotorway.getLaneTotal();
        // 设置默认值
        // 第几道数
        if (laneTotal != null) {
            for (int i = 0; i <= laneTotal - 1; i++) {
                numberOfLanesDict.add(String.valueOf(i + 1));
            }
        }
        // 初始化第几道数List
        else {
            numberOfLanesDict.add("1");
        }
        // 辅路
        Integer serviceRoad = roadMotorway.getServiceRoad() == null ? 0 : roadMotorway.getServiceRoad();
        // 第几道数 如果传过来的值为空
        Integer numberOfLanes = roadMotorway.getNumberOfLanes();
        numberOfLanes = numberOfLanes == null ? 1 : numberOfLanes;
        // 车道类型
        Integer laneType = roadMotorway.getLaneType() == null ? 1 : roadMotorway.getLaneType();
        // 车道宽度
        BigDecimal laneWidth = roadMotorway.getLaneWidth() == null ? new BigDecimal("3.25") : roadMotorway.getLaneWidth();
        // 路缘带宽度
        BigDecimal marginalStripWidth = roadMotorway.getMarginalStripWidth() == null ? new BigDecimal("0.25") : roadMotorway.getMarginalStripWidth();

        binding.laneTotal.setValue(roadMotorway.getLaneTotal());
        binding.serviceRoad.setValue(CommonUtils.getDictValue(serviceRoadDict, serviceRoad));
        binding.numberOfLanes.setValue(numberOfLanes);
        binding.laneType.setValue(Enums.LaneTypeEnum.getValueByKey(laneType));
        binding.laneWidth.setValue(laneWidth);
        binding.pavementForm.setValue(Enums.PavementFormEnum.getValueByKey(roadMotorway.getPavementForm()));
        binding.marginalStripWidth.setValue(marginalStripWidth);
        // 显示附件内容
        initViewFile();
    }

    // 设置照片
    private void initViewFile() {
        // 先根据fileId查询附件数据
        if (!CollectionUtils.isEmpty(roadMotorway.getAddIds())) {
            requestFilesByIds(roadMotorway.getAddIds(), this::initAdapterData);
        }
        // 根据业务ID查询附件信息
        else if (StringUtils.isNotEmpty(roadMotorway.getId())) {
            requestFiles(FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_MOTORWAY_FILE_BIZ_TYPE, roadMotorway.getId(), this::initAdapterData);
        }
    }

    // 往照片适配器里面设置图片显示
    private void initAdapterData(List<MediaFile> mediaFileList) {
        if (CollectionUtils.isEmpty(mediaFileList)) {
            return;
        }
        photoSketchUploadIdArr.clear();
        photoSketchFileArr.clear();
        // 添加到文件数组
        photoSketchFileArr.addAll(mediaFileList);
        for (MediaFile mediaFile : photoSketchFileArr) {
            photoSketchUploadIdArr.add(mediaFile.getId());
        }
        // 设置适配器数据源
        photoSketchAdapter.setmMediaFileList(mediaFileList);
    }

    private void initTitleBar() {
        viewModeValue = new ViewModeValue(this, modeFlag, binding.titleBar, binding.llContainer);

        //设置导航栏右侧按钮
        if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::callMoreMenu);
        } else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(modeFlag)
                || Constants.PRESENT_VALUE_FLAG.EDIT.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::appendOrModifyData);
        }
    }

    /**
     * 保存数据
     */
    private void appendOrModifyData() {
        // 车道总数不能为空
        Integer laneTotal = binding.laneTotal.getIntValue();
        if (laneTotal == null || laneTotal < 1) {
            BamToast.showText(this, "请选择车道总数！", false);
            return;
        }

        // 添加路段调查任务ID
        RoadFacilitiesInvestigationTask facilitiesInvestigationTask = roadFacilitiesTaskDTO.getFacilitiesInvestigationTask();
        if (facilitiesInvestigationTask != null && StringUtils.isNotEmpty(facilitiesInvestigationTask.getId())) {
            roadMotorway.setRoadInvestigationTaskId(facilitiesInvestigationTask.getId());
        }
        roadMotorway.setLaneTotal(laneTotal);
        roadMotorway.setServiceRoad(Enums.ServiceRoadEnum.getKeyByValue(binding.serviceRoad.getStringValue()));
        roadMotorway.setNumberOfLanes(binding.numberOfLanes.getIntValue());
        roadMotorway.setLaneType(Enums.LaneTypeEnum.getKeyByValue(binding.laneType.getStringValue()));
        roadMotorway.setLaneWidth(binding.laneWidth.getBigDecimalValue());
        roadMotorway.setPavementForm(Enums.PavementFormEnum.getKeyByValue(binding.pavementForm.getStringValue()));
        roadMotorway.setMarginalStripWidth(binding.marginalStripWidth.getBigDecimalValue());
        roadMotorway.setAddIds(photoSketchUploadIdArr);
        roadMotorway.setRemoveIds(deletePhotoIdArr);
        roadFacilitiesTaskDTO.setRoadMotorway(roadMotorway);

        Log.i("机动车道app", JSONObject.toJSONString(roadFacilitiesTaskDTO));
        Intent intent = new Intent();
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(modeFlag, roadFacilitiesTaskDTO);
        intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
        setResult(Constants.RESULT_CODE.NEED_REFRESH, intent);
        finish();
    }

    private void callMoreMenu() {
        CommonUtils.showMoreMenu(this, binding.titleBar.getRightLayout(), this::linkToEditActivity, this::deleteData);
    }

    private void deleteData() {

    }

    private void linkToEditActivity() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            //拍照返回，或者视频录制返回
            if (isAdapterImagePickerResult(requestCode, photoSketchAdapter)) {
                ArrayList<MediaFile> mediaFileList = getMediaFileListWhenOnActivityResult(requestCode, data, photoSketchAdapter);
                saveFileAndRefreshAdapter(mediaFileList, photoSketchUploadIdArr, photoSketchAdapter,
                        FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_MOTORWAY_FILE_BIZ_TYPE);
            }
        }
    }

    @OnClick({R.id.laneTotal, R.id.serviceRoad, R.id.numberOfLanes, R.id.laneType, R.id.pavementForm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.laneTotal:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, laneTotalDict, binding.laneTotal.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.laneTotal.setValue(laneTotalDict.get(index));

                        // 给"第几道数"选项动态赋值
                        numberOfLanesDict = new ArrayList<>();
                        for (int i = 0; i <= index; i++) {
                            numberOfLanesDict.add(String.valueOf(i + 1));
                        }
                        // 给"第几道数"设置选中值
                        // 获取"第几道数"的数据
                        Integer numberOfLanesStr = binding.numberOfLanes.getIntValue();
                        // 如果"第几车道" > 车道总数，需要将"第几车道"的默认值设置为1
                        if (numberOfLanesStr > binding.laneTotal.getIntValue()) {
                            binding.numberOfLanes.setValue(1);
                        }
                    }
                });
                break;
            case R.id.serviceRoad:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, serviceRoadDict, binding.serviceRoad.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.serviceRoad.setValue(serviceRoadDict.get(index));
                    }
                });
                break;
            case R.id.numberOfLanes:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, numberOfLanesDict, binding.numberOfLanes.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.numberOfLanes.setValue(numberOfLanesDict.get(index));
                    }
                });
                break;
            case R.id.laneType:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, laneTypeDict, binding.laneType.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.laneType.setValue(laneTypeDict.get(index));
                    }
                });
                break;
            case R.id.pavementForm:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, pavementFormDict, binding.pavementForm.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.pavementForm.setValue(pavementFormDict.get(index));
                    }
                });
                break;
        }
    }


}